<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Contract as ContractModer;
use app\admin\model\User;
use think\Db;
use think\Exception;

/**
 * 文档管理
 *
 * @icon   fa fa-list
 */
class Contract extends Backend
{

    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ContractModer();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['add_time'] = time();
            $result = $this->model->insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }

    /**
     * 生成合同
     *
     * @return string
     * @throws \think\Exception
     */
    public function send_contract($ids)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {

            $word  = $this->getWord(str_replace('https://oa.yuxiang123.cn','.',$row['url']));
            $arr = [];
            foreach ($word as $v) {
                if (strpos($v, '${') !== false) {
                    $res = explode('${',$v);
                    foreach ($res as $vo) {
                        if (strpos($vo, '}') !== false) {
                            $info = explode('}',$vo);
                            $arr[] = $info[0]; 
                        }
                    }
                }
            }
            $this->view->assign('arr', $arr);
            $this->view->assign('row', $row);
            $this->assignconfig('row', $row);
          
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
 /**
     * 生成合同
     *
     * @return string
     * @throws \think\Exception
     */
    public function contract_download($ids)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $params = $this->request->post();
        $arr = [];
        foreach ($params['data'] as $v){
            if(!$v['value']){
                $this->error($v['name'].'不可为空');
            }
            $arr[$v['name']] = $v['value'];
        }
        
        //模板内 默认的搜索模式宏 ${search-pattern}
        $former = str_replace('https://oa.yuxiang123.cn','.',$row['url']);//要处理的word模板
        $latter = './uploads/word_template/'.date('YmdHis',time()).'.docx';//处理后新生成的文件
        $loadTemplate = new \PhpOffice\PhpWord\TemplateProcessor($former);
        //$setValue = [
        //    'amd' => 'AMD显卡',
        //    'company-name' => '科技有限公司',
        //];
        //$loadTemplate->setValues($setValue);//多个替换
        foreach ($arr as $k => $v){
             $loadTemplate->setValue($k, $v);//单个替换    
        }
        $loadTemplate->saveAs($latter);
        $this->success('操作成功','',['url'=>$latter,'title'=>$row['title']]);
    }
    
    public function download($file_url,$title)
    {

        $file_type=explode('.', $file_url);
        $file_type=$file_type[count($file_type)-1];
        $file_type=fopen($file_url, 'r'); //打开文件
        //输入文件标签
        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".filesize($file_url));
        header("Content-Disposition:attchment; filename=".$title.".docx");
        //输出文件内容
        echo fread($file_type, filesize($file_url));
        fclose($file_type);
        exit();
    }

     /**
     * 获取word文档内容
     * @param string $wordPath
     * @return array
     */
    public function getWord($wordPath = '')
    {
        
        //加载word文档，使用phpword处理
        $word = \PhpOffice\PhpWord\IOFactory::load($wordPath);
        
        return $this->getNodeContent($word);
    }
    
    /**
     * 根据word主节点获取分节点内容
     * @param $word
     * @return array
     */
    public function getNodeContent($word)
    {
        $return = [];
        //分解部分
        foreach ($word->getSections() as $section)
        {
            if ($section instanceof \PhpOffice\PhpWord\Element\Section) {
                //分解元素
                foreach ($section->getElements() as $element)
                {
                    //文本元素
                    if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
                        $text = '';
                        foreach ($element->getElements() as $ele) {
                            $text .= $this->getTextNode($ele);
                        }
                        $return[] = $text;
                    }
                    //表格元素
                    else if ($element instanceof \PhpOffice\PhpWord\Element\Table) {
                        foreach ($element->getRows() as $ele)
                        {
                            $return[] = $this->getTableNode($ele);
                        }
                    }
                }
            }
        }
        return $return;
    }
    
    /**
     * 获取文档节点内容
     * @param $node
     * @return string
     */
    public function getTextNode($node)
    {
        $return = '';
        //处理文本
        if ($node instanceof \PhpOffice\PhpWord\Element\Text)
        {
            $return .= $node->getText();
        }
        //处理图片
        else if ($node instanceof \PhpOffice\PhpWord\Element\Image)
        {
            $return .= $this->pic2text($node);
        }
        //处理文本元素
        else if ($node instanceof \PhpOffice\PhpWord\Element\TextRun) {
            foreach ($node->getElements() as $ele) {
                $return .= $this->getTextNode($ele);
            }
        }
        return $return;
    }
    
    /**
     * 获取表格节点内容
     * @param $node
     * @return string
     */
    public function getTableNode($node)
    {
        $return = '';
        //处理行
        if ($node instanceof \PhpOffice\PhpWord\Element\Row) {
            foreach ($node->getCells() as $ele)
            {
                $return .= $this->getTableNode($ele);
            }
        }
        //处理列
        else if ($node instanceof \PhpOffice\PhpWord\Element\Cell) {
            foreach ($node->getElements() as $ele)
            {
                $return .= $this->getTextNode($ele);
            }
        }
        return $return;
    }
    
    /**
     * 处理word文档中base64格式图片
     * @param $node
     * @return string
     */
    public function pic2text($node)
    {
        //获取图片编码
        $imageData = $node->getImageStringData(true);
        //添加图片html显示标头
        $imageData = 'data:' . $node->getImageType() . ';base64,' . $imageData;
        $return = '<img src="'.$imageData.'">';
        return $return;
    }
}
